var App = require('app');

App.FormEditController = Em.ObjectController.extend({

	addOption: function (context) {
		var puid = context.get('group');				
		var p = Vari.fieldMap.get(puid);
		var options = p.get("options");
		var pos = options.indexOf(context) + 1;
		var newOption = Ember.Object.create();
		
		Ember.mixin(newOption, {			
			id: 0,
			uid:  Math.uuid(),
			group: context.get('group'),

			label: context.get("label"), 
			valuee: context.get("valuee"),
			isChecked: context.get("isChecked"),

			code: context.get("code"),
			indexx: context.get("indexx") + 1,
			required: context.get("required"),
			status: context.get("status")
		});
		p.get("options").insertAt(pos, newOption);
		
		p.get("options").forEach(function(item, index) {
			item.set("indexx", index * 10);
		});
	},
	delOption: function (context) {
		var puid = context.get('group');				
		var p = Vari.fieldMap.get(puid);
		var options = p.get("options");
		if (options.length == 1) {
			alert("At least has one option!");
			return;
		}		
		
		options.removeObject(context);
	},
	
    addField: function(filedNo) {
    	FieldUtil.addField(filedNo);
    },
    editFieldSettings: function(uid) {
    	// by clicking the tab
    	FieldUtil.editFieldSettings(uid);
    },
    editFormSettings: function(formId) {    	
    	FormUtil.editFormSettings(formId);
    },
    
    saveForm: function() {
       	var me = this;
       	var formId = Vari.frm.get("id");
       	var type = null;
       	if (formId == null) {
       		type = "POST";
	       	Ember.mixin(Vari.frm, {
		   		appId: Vari.CurrAppId 
		   	});
		} else {
			type = "PUT";
		}
    	var json = $.toJSON(Vari.frm);

    	$.ajax({
			type : type,
			dataType: 'json',
			contentType: 'application/json; charset=utf-8',

			async : false,
			url : Vari.ApiRestV1 + 'forms',
			data : json,

			success : function(json) {
				Vari.CurrFormId = json.frmId;
				Vari.frm = FormUtil.retriveInfo(Vari.CurrFormId);				
				me.set('content', Vari.frm);
				new $.Zebra_Dialog('<strong>Sucess</strong> to save the form!', {
				    'buttons':  false,
				    'modal': false,
				    'position': [],
				    'auto_close': 1000
				});
			}
		});
    }
});